package com.etcbase.dcs.controller.map;

import java.io.ByteArrayOutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.google.android.maps.GeoPoint;

/*
 *  Async-task to get street address with GOOGLE REVERSE GEOCODING API
 *  Implement OnGetLocationAddressListener and register it to receive the address when available 
 */
public class MapLocationAsyncTask extends AsyncTask<GeoPoint, Object, String> {
	public static final String TAG = MapLocationAsyncTask.class.getSimpleName();
	
	public interface OnGetLocationAddressListener {
		public void onGetLocationAddress(String city, String district, String address);
	}
	public void setOnGetLocationAddressListener( OnGetLocationAddressListener listener ) {
		onGetLocationAddressListener = listener;
	}
	
	private OnGetLocationAddressListener onGetLocationAddressListener = null;
	
	private String getQueryResult(GeoPoint p) throws Exception {		
		//String queryAddress = "http://maps.googleapis.com/maps/api/geocode/json?latlng=41.15,29.005&sensor=true";
		String queryAddress = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" +
				Double.toString(p.getLatitudeE6()/1E6) + "," +
				Double.toString(p.getLongitudeE6()/1E6) + "&sensor=true" + "&language=tr";
		String responseString = null;
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpResponse response = httpclient.execute( new HttpGet(queryAddress) );
	    StatusLine statusLine = response.getStatusLine();
	    int statusCode = statusLine.getStatusCode();
	    if(statusCode == HttpStatus.SC_OK){
	        ByteArrayOutputStream out = new ByteArrayOutputStream();
			response.getEntity().writeTo(out);
			out.close();
	        responseString = out.toString();
	        //..more logic
	    } else {
	        //Closes the connection.
	    	Log.d( TAG, "THERE WAS SOME ERROR = " + statusCode, null );
	    	response.getEntity().getContent().close();
	    }
	    
	    return responseString;
	}


	@Override
	protected String doInBackground(GeoPoint... params) {
		try {
			return getQueryResult(params[0]);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	protected void onPostExecute(String result) {
		String city = null;
		String district = null;
		String address = null;

		try {
			JSONObject jsonObject = new JSONObject(result);
			JSONArray results = jsonObject.getJSONArray("results");				
			JSONObject first = results.getJSONObject(0);
			address = first.getString("formatted_address");
			
			JSONArray components = first.getJSONArray("address_components");
			
			for( int i=0; i<components.length(); i++ ) {
				JSONObject subData = components.getJSONObject(i);
				
				JSONArray types = subData.getJSONArray("types");
				String type = types.getString(0);
				
				if ( type.equals("administrative_area_level_1") ) {
					city = subData.getString("long_name");
				} else if ( type.equals("administrative_area_level_2") ) {
					district = subData.getString("long_name");
				} else if ( type.equals("sublocality") ) {
					district = subData.getString("long_name");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			Log.d(TAG, "ERROR PARSING THE JSON-OBJECT!");
		}
		
		if (onGetLocationAddressListener != null) {
			onGetLocationAddressListener.onGetLocationAddress(city, district, address);
		}
	}
}